package com.example.demo.practice.mychart;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.demo.practice.R;
import com.example.demo.practice.chatview.SingleView;
import com.example.demo.practice.httpserver.HttpServer;
import com.example.demo.practice.ui.PieChart_View;
import com.example.demo.practice.ui.TitleView;
import com.example.demo.practice.ui.PieChartBean;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class EtpDistribute extends AppCompatActivity {
    private HttpServer http = new HttpServer();
    private String HTTP = http.getHttp();
    private JSONArray jSONArray;

    private SingleView mMySingleChartView;
    private List<Float> singlelist;
    private RelativeLayout relativeLayout;
    private List<Integer> horList;
    private LinearLayout llSingle;
    private RelativeLayout rlSingle;
    private PieChart_View lv;

    private ArrayList<String> regions = new ArrayList<>();
    private ArrayList<Integer> etp_number = new ArrayList<>();
    private ArrayList<String> type = new ArrayList<>();
    private ArrayList<Integer> type_number = new ArrayList<>();
    private ArrayList<String > color = new ArrayList<>();

    private TitleView title;
    private TextView names;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getSupportActionBar().hide();
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.etp_distrubute);
        title = (TitleView) findViewById(R.id.title_text_tv);
        title.setText("设备分布");

        color.add("#fe996b");
        color.add("#00d4bd");
        color.add("#f868ae");
        color.add("#a65ced");
        color.add("#01c6fd");
        color.add("#c076f1");
        color.add("#00d1fc");
        color.add("#00dcfe");
        regions.add("高新区");
        regions.add("中原区");
        regions.add("金水区");
        regions.add("经济技术开发区");
        regions.add("二七区");
        regions.add("上街区");
        regions.add("回族管城区");
        regions.add("惠济区");
        etp_number.add(1);
        for (int i = 1;i < regions.size();i++){
            etp_number.add(random());
        }

        relativeLayout = (RelativeLayout) findViewById(R.id.linearLayout);
        lv = (PieChart_View) findViewById(R.id.pie_view);
        horList = new ArrayList<>();

        getVideoData();
    }

    /**
     * 初始化单柱柱状图
     */
    private void initSingle(){
        mMySingleChartView = (SingleView) findViewById(R.id.my_single_chart_view);
        rlSingle = (RelativeLayout) findViewById(R.id.rl_single);
        singlelist = new ArrayList<>();
        Random random = new Random();
        while (singlelist.size() < 12) {
            int randomInt = random.nextInt(100);
            singlelist.add((float) randomInt);
        }

        mMySingleChartView.setRegions(regions);
        mMySingleChartView.setList(etp_number);
        rlSingle.removeView(llSingle);
        lv.setPieName(regions.get(0)+etp_number.get(0)+"个");
        initHorzion(etp_number.get(0),0);
        //原理同双柱
        mMySingleChartView.setListener(new SingleView.getNumberListener() {
            @Override
            public void getNumber(int number, int x, int y) {
                rlSingle.removeView(llSingle);
                llSingle = (LinearLayout) LayoutInflater.from(EtpDistribute.this).inflate(R.layout.layout_pro_expense, null);

                lv.setPieName(regions.get(number)+etp_number.get(number)+"个");
                initHorzion(etp_number.get(number),number);


                llSingle.measure(0, 0);
                RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT);
                params.leftMargin = x - 100;
                if (x - 100 < 0) {
                    params.leftMargin = 0;
                } else if (x - 100 > relativeLayout.getWidth() - llSingle.getMeasuredWidth()) {
                    params.leftMargin = relativeLayout.getWidth() - llSingle.getMeasuredWidth();
                }

                llSingle.setLayoutParams(params);
                rlSingle.addView(llSingle);
            }
        });
    }


    private void initHorzion(int num,int numb){
        horList.clear();
        if (numb == 0){
            for (int i=0;i<type.size();i++){
                horList.add(type_number.get(i));
            }
        }else{
            int ave = num/(type.size()-1);
            for (int i=0;i<type.size()-1;i++){
                horList.add(ave);
            }
            horList.add(num - (type.size()-1)*ave);
        }
        ArrayList<PieChartBean> lists = new ArrayList<>();
        lists.clear();

        for (int nu = 0;nu < type.size();nu ++){
            lists.add(new PieChartBean(Color.parseColor(color.get(nu)), horList.get(nu), type.get(nu)+horList.get(nu)+"个"));
        }
        lv.setData(lists);

    }

    public int random(){
        Random rand = new Random();
        int n = rand.nextInt(80);
        return n > 4 ? n : random();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            for (int i = 0; i < jSONArray.length(); i++) {
                JSONObject json = null;
                try {
                    json = (JSONObject) jSONArray.get(i);
                    String name = json.getString("name");

                    etp_number.set(0,etp_number.get(0) + 1);

                    int n = 0;
                    for (int j = 0;j < type.size();j++){
                        if (type.get(j).equals(name))
                        {
                            type_number.set(j,type_number.get(j) + 1);
                            n++;
                            break;
                        }
                    }
                    if (n == 0){
                        type.add(name);
                        type_number.add(1);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            jSONArray=null;

            initSingle();

            super.handleMessage(msg);
        }
    };

    private void getVideoData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象
                    Request request = new Request.Builder()
                            .url(HTTP + "getFacilities")//请求接口。如果需要传参拼接到接口后面。
                            .build();//创建Request 对象

                    Response response = client.newCall(request).execute();//得到Response 对象
                    if (response.isSuccessful()) {
                        Log.e("kwwl", "response.code()==" + response.code());
                        Log.e("kwwl", "response.message()==" + response.message());
                        //response.body().string()只可以调用一次
                        //此时的代码执行在子线程，修改UI的操作请使用handler跳转到UI线程。
                        jSONArray = new JSONArray(response.body().string());
                        handler.sendEmptyMessage(0);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
